package zmee.common.handler;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.scm.common.constant.BillAssistConstant;
import kd.scm.pds.common.constant.SrcCommonConstant;
import kd.scm.pds.common.constant.SrcMetadataConstant;
import kd.scm.pds.common.util.PdsCommonUtils;
import kd.scm.src.common.calc.SrcCalcContext;
import kd.scm.src.common.calc.SrcCalcHelper;
import kd.scm.src.common.calc.rank.ISrcRankCoreCalc;
import kd.scm.src.common.calc.rank.SrcRankFacade;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 综合计算--排名计算--计算最终得分(浙江物产临时插件)
 *
 * @author rd_fumin_huang
 */
public class SrcRankCalcFinalScore_zjwc2 implements ISrcRankCoreCalc {

    @Override
    public void process(SrcCalcContext context) {
        // 计算最终得分
        calcFinalScore(context);
    }

    /**
     * 计算最终得分
     *
     * @param context
     */
    protected void calcFinalScore(SrcCalcContext context) {
        // 自动 评标汇总分录
        List<DynamicObject> assessList = new ArrayList<DynamicObject>(16);
        // 手工 评标汇总分录
        List<DynamicObject> manualScoreList = new ArrayList<DynamicObject>(16);

        // 从分组key拆分分组标段、分组标的
        Map<String, Object> groupIdMap = SrcCalcHelper.getRankObjectIdFromKey(context.getSumType(), context.getCurrGKey());
        long groupPackageId = PdsCommonUtils.object2Long(groupIdMap.get(SrcCommonConstant.PACKAGEID));
        long groupPurlistId = PdsCommonUtils.object2Long(groupIdMap.get(SrcCommonConstant.PURLISTID));

        // 计算得分并写入到 评标汇总表
        for (String key : context.getRankValueMap().keySet()) {
            // 从key拆分供应商、标段、标的
            Map<String, Object> idMap = SrcCalcHelper.getRankObjectIdFromKey(context.getSumType(), key);
            long supplierId = PdsCommonUtils.object2Long(idMap.get(SrcCommonConstant.SUPPLIERID));
            long packageId = PdsCommonUtils.object2Long(idMap.get(SrcCommonConstant.PACKAGEID));
            long purlistId = PdsCommonUtils.object2Long(idMap.get(SrcCommonConstant.PURLISTID));
            long purlistId0 = purlistId;

            // 按标段汇总
            if (context.getSumType().equals(SrcCommonConstant.SUMTYPE_PACKAGE)) {
                if (packageId != groupPackageId) {
                    continue; // 标段不匹配，跳过不处理
                }
            } else
                // 按标段+标的 汇总
                if (context.getSumType().equals(SrcCommonConstant.SUMTYPE_PURLIST)) {
                    if (packageId != groupPackageId || purlistId != groupPurlistId) {
                        continue; // 标段+标的 不匹配，跳过不处理
                    } else {
                        // 如果按标的，这里需要再拆分 供应商id 和 分录id，并以 分录id 作为 purlistID
                        String[] splitKey = ((String) idMap.get(SrcCommonConstant.SUPPLIERID)).split("\\_");
                        supplierId = PdsCommonUtils.object2Long(splitKey[0]);
                        long entryId = PdsCommonUtils.object2Long(splitKey[1]);
                        // 采购清单分录id和标的id对应关系，暂存到 Map
                        context.getEntryid_PurlistidMap().put(entryId, purlistId);
                        purlistId = entryId;
                    }
                }

            BigDecimal bizAmount = context.getRankValueMap().get(key);
            BigDecimal bizAmountRounded = bizAmount.setScale(6, BigDecimal.ROUND_HALF_UP);

            // 自动计算商务得分
            BigDecimal bizScore = BigDecimal.ZERO;
            // 非赠品, 才需要计算 商务得分
            if (!context.getPresentSet().contains(purlistId)) {
                getBizScore(context, key);
            }

            // 创建手工评分结果分录，并返回原来的商务得分（如果已存在）
            bizScore = createManualScore(context, manualScoreList, supplierId, packageId, purlistId, bizScore, bizAmountRounded);

            // 创建系统评分结果分录
            createSystemScore(context, assessList, supplierId, packageId, purlistId, bizScore, bizAmountRounded, purlistId0);
        }
        context.setAssessList(assessList);
        context.setManualScoreList(manualScoreList);
    }

    /**
     * 创建手工评分结果分录，并返回原来的商务得分（如果已存在）
     */
    protected BigDecimal createManualScore(SrcCalcContext context, List<DynamicObject> manualScoreList, long supplierId, long packageId, long purlistId, BigDecimal bizScore, BigDecimal bizAmountRounded) {
        // 如果需要手工录入商务得分
        if (!context.isManualScore()) {
            return bizScore;
        }
        // 标段+供应商 是否存在 回标详情中，若不存在，则不处理
        if (context.getTenderSupplierSet().size() > 0) {
            String pkg_supKey = null;
            if (SrcCommonConstant.MANAGETYPE_BYPACKAGE.equals(context.getManageType())) {
                pkg_supKey = String.valueOf(packageId) + '_' + String.valueOf(supplierId);
            } else {
                pkg_supKey = String.valueOf(String.valueOf(supplierId));
            }
            if (!context.getTenderSupplierSet().contains(pkg_supKey)) {
                return bizScore;
            }
        }

        QFilter bizScorefilters = new QFilter(BillAssistConstant.BILL_ID, QCP.equals, context.getBillId()).and(BillAssistConstant.SUPPLIER_ID, QCP.equals, supplierId).and(SrcCommonConstant.PACKAGE_ID, QCP.equals, packageId).and(SrcCommonConstant.PURLIST_ID, QCP.equals, purlistId);
        DynamicObject bizScoreobj = QueryServiceHelper.queryOne(SrcMetadataConstant.SRC_MANUALSCORE_META, SrcCommonConstant.ID, bizScorefilters.toArray());
        if (bizScoreobj != null) {
            // 如果已经存在，重新装载数据（以便保存）
            bizScoreobj = BusinessDataServiceHelper.loadSingle(bizScoreobj.getLong(SrcCommonConstant.ID), SrcMetadataConstant.SRC_MANUALSCORE_META);
            // 取原来的商务得分
            bizScore = bizScoreobj.getBigDecimal(SrcCommonConstant.BIZSCORE);
        } else {
            // 否则，创建新的一条记录
            bizScoreobj = BusinessDataServiceHelper.newDynamicObject(SrcMetadataConstant.SRC_MANUALSCORE_META);
            bizScoreobj.set(BillAssistConstant.BILL_ID, context.getBillId());
            bizScoreobj.set(SrcCommonConstant.PARENTID, context.getBillId());
            bizScoreobj.set(BillAssistConstant.FSEQ, context.getIndex());
            bizScoreobj.set(BillAssistConstant.SUPPLIER_ID, supplierId);
            bizScoreobj.set(SrcCommonConstant.SUPPLIERTYPE, context.getSupTypeMap().get(String.valueOf(supplierId))); // 供应商类别
            bizScoreobj.set(SrcCommonConstant.PACKAGE_ID, packageId);
            bizScoreobj.set(SrcCommonConstant.PURLIST_ID, purlistId);
            bizScoreobj.set(SrcCommonConstant.BIZSCORE, bizScore);
        }
        // 更新 商务价格
        bizScoreobj.set(SrcCommonConstant.BIZAMOUNT, bizAmountRounded);
        // 添加到List
        manualScoreList.add(bizScoreobj);
        // 返回商务得分
        return bizScore;
    }

    /**
     * 创建系统评分结果分录
     */
    protected void createSystemScore(SrcCalcContext context, List<DynamicObject> assessList, long supplierId, long packageId, long purlistId, BigDecimal bizScore, BigDecimal bizAmountRounded, long purlistId0) {
        // 创建 自动评分结果 新的分录
        DynamicObject entryObj = BusinessDataServiceHelper.newDynamicObject(SrcMetadataConstant.SRC_BIDASSESS_BIZ);
        entryObj.set(BillAssistConstant.BILL_ID, context.getBillId());
        entryObj.set(SrcCommonConstant.PARENTID, context.getBillId());
        entryObj.set(BillAssistConstant.FSEQ, context.getIndex());
        entryObj.set(BillAssistConstant.SUPPLIER_ID, supplierId);
        entryObj.set(SrcCommonConstant.SUPPLIERTYPE, context.getSupTypeMap().get(String.valueOf(supplierId))); // 供应商类别
        entryObj.set(SrcCommonConstant.PKGGROUP, context.getPkgGroupId());// 标段分组
        entryObj.set(SrcCommonConstant.PACKAGE_ID, packageId);
        entryObj.set(SrcCommonConstant.PURLIST_ID, purlistId);
        entryObj.set(SrcCommonConstant.PURLISTID0, purlistId0); // 原始采购清单ID
        entryObj.set(SrcCommonConstant.BIZAMOUNT, bizAmountRounded);
        entryObj.set(SrcCommonConstant.MINVALUE, context.getMinValue().setScale(6, BigDecimal.ROUND_HALF_UP));
        entryObj.set(SrcCommonConstant.MAXVALUE, context.getMaxValue().setScale(6, BigDecimal.ROUND_HALF_UP));
        entryObj.set(SrcCommonConstant.AVGVALUE, context.getAvgValue().setScale(6, BigDecimal.ROUND_HALF_UP));

        // entryObj.set(SrcCommonConstant.BIZSCORE,
        // bizScore.multiply(context.getRatio_biz()).setScale(6,
        // BigDecimal.ROUND_HALF_UP));
        BigDecimal bizScore2 = bizScore.add(context.getRatio_biz().multiply(new BigDecimal(100))).subtract(new BigDecimal(100));
        entryObj.set(SrcCommonConstant.BIZSCORE, bizScore2);

        context.setSupplierId(supplierId);
        context.setPackageId(packageId);
        context.setPurlistId(purlistId);

        // 计算 技术得分、商务得分、商务综合得分
        Map<String, BigDecimal> scoreMap = SrcCalcHelper.getTecAndBizAndOthScore(context);

        BigDecimal tecScore = scoreMap.get(SrcCommonConstant.TECSCORE);
        BigDecimal othScore = scoreMap.get(SrcCommonConstant.OTHSCORE);
        entryObj.set(SrcCommonConstant.TECSCORE, tecScore.setScale(6, BigDecimal.ROUND_HALF_UP));
        entryObj.set(SrcCommonConstant.OTHSCORE, othScore.setScale(6, BigDecimal.ROUND_HALF_UP));

        BigDecimal weightScore = BigDecimal.ZERO;
        // 是线下评分, 并且不是 手工录入商务得分
        if (context.getScoretype().equals("2") && !context.isManualScore()) {
            // 线下评标录入时，已限制得分不能超过指标占比，这里不需要再处理 2022-07-09 HFM
            tecScore = scoreMap.get(SrcCommonConstant.TECSCORE); // .multiply(context.getRatio_tec());
            bizScore = scoreMap.get(SrcCommonConstant.BIZSCORE); // .multiply(context.getRatio_biz());
            othScore = scoreMap.get(SrcCommonConstant.OTHSCORE); // .multiply(context.getRatio_oth());
            entryObj.set(SrcCommonConstant.TECSCORE, tecScore.setScale(6, BigDecimal.ROUND_HALF_UP));
            entryObj.set(SrcCommonConstant.BIZSCORE, bizScore.setScale(6, BigDecimal.ROUND_HALF_UP));
            entryObj.set(SrcCommonConstant.OTHSCORE, othScore.setScale(6, BigDecimal.ROUND_HALF_UP));
            weightScore = (tecScore).add(bizScore).add(othScore);
        } else {
            // 如果是手工评商务得分
            if (context.isBizScore()) {
                BigDecimal newBizScore = scoreMap.get(SrcCommonConstant.BIZSCORE);
                entryObj.set(SrcCommonConstant.BIZSCORE, newBizScore.setScale(6, BigDecimal.ROUND_HALF_UP));
                // 分数不需要×技术占比
                weightScore = (tecScore).add(newBizScore).add(othScore);
            } else {
                // 计算 总得分（权重计算）
                // weightScore =
                // (tecScore).add(bizScore.multiply(context.getRatio_biz())).add(othScore);
                weightScore = (tecScore).add(bizScore2).add(othScore);
            }
        }
        entryObj.set(SrcCommonConstant.SUMSCORE, weightScore.setScale(6, BigDecimal.ROUND_HALF_UP));

        // 如果手工录入评标结果，从之前数据取值
        reSetBizAssessScore(context, entryObj);

        // 添加到List
        assessList.add(entryObj);
        // 序号加1
        context.setIndex(context.getIndex() + 1);
    }

    /**
     * 如果手工录入评标结果，从之前数据取值
     */
    private void reSetBizAssessScore(SrcCalcContext context, DynamicObject entryObj) {
        if (context.getPreBidAssessMap() != null && context.getPreBidAssessMap().size() > 0) {
            String key = String.valueOf(context.getSupplierId()) + '_' + String.valueOf(context.getPackageId()) + '_' + String.valueOf(context.getPurlistId());
            DynamicObject preObj = context.getPreBidAssessMap().get(key);
            if (null != preObj) {
                entryObj.set(SrcCommonConstant.TECSCORE, preObj.getBigDecimal(SrcCommonConstant.TECSCORE));
                entryObj.set(SrcCommonConstant.BIZSCORE, preObj.getBigDecimal(SrcCommonConstant.BIZSCORE));
                entryObj.set(SrcCommonConstant.OTHSCORE, preObj.getBigDecimal(SrcCommonConstant.OTHSCORE));
                entryObj.set(SrcCommonConstant.SUMSCORE, preObj.getBigDecimal(SrcCommonConstant.SUMSCORE));
            }
        }
    }

    /**
     * 获取 商务得分
     *
     */
    protected void getBizScore(SrcCalcContext context, String key) {
        // 如果手工评商务分，直接返回0
        if (context.isBizScore()) {
            return;
        }

        BigDecimal bizAmount = context.getRankValueMap().get(key);
        BigDecimal baseAmount = BigDecimal.ZERO;

        switch (context.getRankCalcType()) {
            // 基于最小值
            case SrcCommonConstant.RANKTYPE_MIN:
            case SrcCommonConstant.RANKTYPE_RANDOM:
                baseAmount = context.getMinValue();
                break;

            // 基于最大值
            case SrcCommonConstant.RANKTYPE_MAX:
                baseAmount = context.getMaxValue();
                break;

            // 基于平均值
            case SrcCommonConstant.RANKTYPE_AVG:
                baseAmount = context.getAvgValue();
                break;
            default:
                break;
        }

        // 投标价、基准价 都大于0，才能计算得分，否则返回0
        if (bizAmount.compareTo(BigDecimal.ZERO) > 0 && baseAmount.compareTo(BigDecimal.ZERO) > 0) {
            // 根据公式计算商务得分 （核心算法外挂到扩展插件）
//            return SrcRankFacade.autoCalcBizSscore(context, bizAmount, baseAmount);
            SrcRankFacade.autoCalcBizSscore(context);
        }
    }
}
